package com.haibara.aioj.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.haibara.aioj.annotation.AuthCheck;
import com.haibara.aioj.common.*;
import com.haibara.aioj.constant.CommonConstant;
import com.haibara.aioj.constant.UserConstant;
import com.haibara.aioj.exception.BusinessException;
import com.haibara.aioj.exception.ThrowUtils;
import com.haibara.aioj.mapper.QuestionSubmitMapper;
import com.haibara.aioj.model.dto.question.*;
import com.haibara.aioj.model.dto.questionsubmit.JudgeInfo;
import com.haibara.aioj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.haibara.aioj.model.dto.questionsubmit.QuestionSubmitQueryPageRequest;
import com.haibara.aioj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.haibara.aioj.model.dto.user.UserQueryRequest;
import com.haibara.aioj.model.entity.Question;
import com.haibara.aioj.model.entity.QuestionSubmit;
import com.haibara.aioj.model.entity.User;
import com.haibara.aioj.model.enums.QuestionSubmitLanguageEnum;
import com.haibara.aioj.model.enums.QuestionSubmitStatusEnum;
import com.haibara.aioj.model.enums.ResultCodeEnum;
import com.haibara.aioj.model.vo.JudgeVO;
import com.haibara.aioj.model.vo.QuestionSubmitVO;
import com.haibara.aioj.model.vo.QuestionSubmitViewVO;
import com.haibara.aioj.model.vo.QuestionVO;
import com.haibara.aioj.service.QuestionService;
import com.haibara.aioj.service.QuestionSubmitService;
import com.haibara.aioj.service.UserService;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import static com.haibara.aioj.constant.RedisKey.*;


@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private QuestionSubmitMapper questionSubmitMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1.从QuestionAddRequest中获取信息
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        List<String> tags = questionAddRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionAddRequest.getJudgeCase();
        if(judgeCase != null && !judgeCase.isEmpty()){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionAddRequest.getJudgeConfig();
        if(judgeConfig != null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        // 2.设置题目默认信息
        questionService.validQuestion(question, true);
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setExampleCode(questionAddRequest.getExampleCode());
        question.setAcceptedNum(0);
        question.setSubmitNum(0);
        boolean result = questionService.save(question);
        // 将数据放入Redis
        delRedisInfo(question.getId());
        putRedisInfo(question);

        // 3.向代码沙箱发送JudgeCode
        QuestionCode questionCode = new QuestionCode();
        questionCode.setQuestionId(question.getId());
        questionCode.setCode(questionAddRequest.getJudgeCode());
        addJudgeCode(questionCode);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 向沙箱发送JudgeCode
     * @param questionCode
     */
    private void addJudgeCode(QuestionCode questionCode){
        String url = "http://localhost:8090/codesandbox/getCode";
        String json = JSONUtil.toJsonStr(questionCode);
        HttpUtil.createPost(url)
                .body(json)
                .execute();
    }

    /**
     * 删除
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人且管理员可删除
        if(!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        if(!oldQuestion.getUserId().equals(user.getId())){
            throw new BusinessException(ErrorCode.ONLY_CREATOR_ERROR);
        }
        boolean b = questionService.removeById(id);
        // 将Redis中的数据删除
        delRedisInfo(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionUpdateRequest.getJudgeCase();
        if(judgeCase != null && !judgeCase.isEmpty()){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
        if(judgeConfig != null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        // 判断是否存在
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);

        // 将修改后的JudgeCode发送给沙箱
        QuestionCode questionCode = new QuestionCode();
        questionCode.setQuestionId(question.getId());
        questionCode.setCode(question.getJudgeCode());
        addJudgeCode(questionCode);

        boolean result = questionService.updateById(question);
        question.setSubmitNum(oldQuestion.getSubmitNum());
        question.setAcceptedNum(oldQuestion.getAcceptedNum());
        question.setUserId(oldQuestion.getUserId());
        question.setCreateTime(oldQuestion.getCreateTime());
        delRedisInfo(question.getId());
        putRedisInfo(question);
        return ResultUtils.success(result);
    }

    // 操作Redis
    private void delRedisInfo(Long questionId){
        stringRedisTemplate.opsForZSet().remove(pageQuestionKey,questionId.toString());
        stringRedisTemplate.delete(questionKey+questionId);
    }

    private void putRedisInfo(Question question){
        QuestionVO questionVO = QuestionVO.objToVo(question);
        stringRedisTemplate.opsForZSet().add(pageQuestionKey,questionVO.getId().toString(),questionVO.getId());
        stringRedisTemplate.opsForValue().append(questionKey+questionVO.getId(),JSONUtil.toJsonStr(questionVO));
    }

    /**
     * 根据 id 获取 题目VO信息
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 获取上一次提交的代码
     * @param id
     * @return
     */
    @GetMapping("/history")
    public String getHistoryCode(long id, HttpServletRequest request) {
        return questionSubmitService.getHistoryCode(id,request);
    }

    /**
     * 获取题目示例代码
     * @param id
     * @return
     */
    @GetMapping("/example")
    public String getExampleCode(long id) {
        return questionSubmitService.getExampleCode(id);
    }

    /**
     * 根据 id 获取 题目信息
     * @param id id
     * @return {@link BaseResponse}<{@link QuestionVO}>
     */
    @GetMapping("/get")
    public BaseResponse<Question> getQuestionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (!question.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(question);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long size = questionQueryRequest.getPageSize();
        long current = (questionQueryRequest.getCurrent() - 1)* size;
        // Redis操作
        if(StrUtil.isBlankIfStr(questionQueryRequest.getTitle()) && questionQueryRequest.getTags().isEmpty()){
            long start = current;
            long end = start+size-1;
            ZSetOperations<String, String> zSet = stringRedisTemplate.opsForZSet();
            // result
            long total = zSet.zCard(pageQuestionKey);
            ArrayList<QuestionVO> questionVOS = new ArrayList<>();

            Set<String> strings = zSet.range(pageQuestionKey, start, end);
            ValueOperations<String, String> value = stringRedisTemplate.opsForValue();

            for (String string : strings) {
                String s = value.get(questionKey+string);
                QuestionVO questionVO = JSONUtil.toBean(s,QuestionVO.class);
                questionVOS.add(questionVO);
            }

            Page<QuestionVO> questionVOPage = new Page<>();
            questionVOPage.setRecords(questionVOS);
            questionVOPage.setTotal(total);
            if(size>0){
                questionVOPage.setPages(total / size);
            }
            return ResultUtils.success(questionVOPage);

        }

        questionQueryRequest.setSortField("id");
        questionQueryRequest.setSortOrder(CommonConstant.SORT_ORDER_ASC);
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 获取Question Page 并将其处理为 QuestionVO Page
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
            HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionEditRequest.getJudgeCase();
        if(judgeCase != null && !judgeCase.isEmpty()){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionEditRequest.getJudgeConfig();
        if(judgeConfig != null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 修改示例代码和判题代码
        question.setExampleCode(questionEditRequest.getExampleCode());
        question.setJudgeCode(questionEditRequest.getJudgeCode());

        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取题目列表（仅管理员）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                   HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }


    // questionSubmit

    @GetMapping("/get/language")
    public BaseResponse<List<String>> getCodeLanguage() {
        return ResultUtils.success(QuestionSubmitLanguageEnum.getValues());
    }

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return resultNum 本次点赞变化数
     */
    @PostMapping("/question-submit/do")
    public BaseResponse<Integer> doSubmit(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest,
                                          HttpServletRequest request) {
        if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 登录才能点赞
        final User loginUser = userService.getLoginUser(request);
        long result = questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser);
        return ResultUtils.success(Math.toIntExact(result));
    }

    /**
     * 分页获取题目提交列表
     * @param questionSubmitQueryRequest
     * @return
     */
    @GetMapping("/question-submit/list/page")
    public BaseResponse<Page<QuestionSubmitViewVO>> listQuestionSubmitByPage(QuestionSubmitQueryPageRequest questionSubmitQueryRequest) {
        long size = questionSubmitQueryRequest.getPageSize();
        long pageIndex = (questionSubmitQueryRequest.getCurrent() - 1) * size;
        String title = questionSubmitQueryRequest.getTitle();
        String language = questionSubmitQueryRequest.getLanguage();
        return ResultUtils.success(questionSubmitService.listQuestionSubmitByPage(title, language, pageIndex, size));
    }

//    @GetMapping("/question-submit/get/id")
//    public BaseResponse<JudgeVO> getJudgeResult(Long questionSubmitId) {
//        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
//        if (ObjectUtil.isEmpty(questionSubmit)) {
//            return ResultUtils.success(new JudgeVO(), "数据为空");
//        }
//        Integer status = questionSubmit.getStatus();
//        if (QuestionSubmitStatusEnum.WAITING.getValue().equals(status)|| QuestionSubmitStatusEnum.RUNNING.getValue().equals(status)) {
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "判题中");
//        }
//        JudgeVO judgeVO = CopyUtil.copy(questionSubmit, JudgeVO.class);
//        JudgeInfo judgeInfo = JSONUtil.toBean(questionSubmit.getJudgeInfo(), JudgeInfo.class);
//        judgeVO.setTime(ObjectUtil.defaultIfNull(judgeInfo.getTime(), 0) + "ms");
//        judgeVO.setMemory(ObjectUtil.defaultIfNull(judgeInfo.getMemory(), 0) + "MB");
//        judgeVO.setMessage(judgeInfo.getMessage());
//        return ResultUtils.success(judgeVO);
//    }

    @GetMapping("/question-submit/get/id")
    public BaseResponse<JudgeVO> getJudgeResult(Long questionSubmitId) {
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        String s = value.get(questionSubmitKey + questionSubmitId);
        // 若s为空则代表没有判题完成
        if (s == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "判题中");
        }
        QuestionSubmitViewVO questionSubmitViewVO = JSONUtil.toBean(s,QuestionSubmitViewVO.class);
        JudgeVO judgeVO = new JudgeVO();
        judgeVO.setLanguage(questionSubmitViewVO.getLanguage());
        judgeVO.setStatus(1);
        JudgeInfo judgeInfo = JSONUtil.toBean(questionSubmitViewVO.getJudgeInfo(), JudgeInfo.class);
        judgeVO.setTime(ObjectUtil.defaultIfNull(judgeInfo.getTime(), 0) + "ms");
        judgeVO.setMemory(ObjectUtil.defaultIfNull(judgeInfo.getMemory(), 0) + "MB");
        judgeVO.setMessage(judgeInfo.getMessage());
        return ResultUtils.success(judgeVO);
    }

    @GetMapping("/getMaxId")
    public int getMaxQuestionId(){
        return questionService.getMaxQuestionId();
    }

    @GetMapping("/init")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void init(){
        // 向代码沙箱发送代码文件
        List<Question> questionList = questionService.list();
        for (Question question : questionList) {
            String code = question.getJudgeCode();
            QuestionCode questionCode = new QuestionCode();
            questionCode.setQuestionId(question.getId());
            questionCode.setCode(code);
            addJudgeCode(questionCode);
        }

        //向Redis中存放数据
        // 删除原有信息
        ZSetOperations<String, String> zSet = stringRedisTemplate.opsForZSet();
        Set<String> range = zSet.range(pageQuestionSubmitKey, 0, -1);
        ArrayList<String> strings = new ArrayList<>();
        for (String s : range) {
            strings.add(questionSubmitKey+s);
        }
        stringRedisTemplate.delete(strings);
        range = zSet.range(pageQuestionKey, 0, -1);
        for (String s : range) {
            strings.add(questionKey+s);
        }
        stringRedisTemplate.delete(strings);
        // Page
        List<Question> questions = questionService.list();
        ZSetOperations<String, String> zset = zSet;
        for (Question question : questions) {
            zset.add(pageQuestionKey,question.getId().toString(),question.getId());
        }
        List<QuestionSubmit> questionSubmits = questionSubmitService.list();
        for (QuestionSubmit questionSubmit : questionSubmits) {
            zset.add(pageQuestionSubmitKey,questionSubmit.getId().toString(),questionSubmit.getCreateTime().getTime());
        }

        // Question & QuestionSubmit
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        Set<Long> userIdSet = questionList.stream().map(Question::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            QuestionVO questionVO = QuestionVO.objToVo(question);
            Long userId = question.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionVO.setUserVO(userService.getUserVO(user));
            return questionVO;
        }).collect(Collectors.toList());
        for (QuestionVO questionVO : questionVOList) {
            stringRedisTemplate.opsForValue().append(questionKey+questionVO.getId(),JSONUtil.toJsonStr(questionVO));
        }

        Long count = zset.zCard(pageQuestionSubmitKey);
        List<QuestionSubmitViewVO> questionSubmitViewVOS = questionSubmitMapper.selectQuestionSubmit(null, null, 0, count-1);
        for (QuestionSubmitViewVO questionSubmitViewVO : questionSubmitViewVOS) {
            String key = questionSubmitKey+questionSubmitViewVO.getQuestionSubmitId();
            value.append(key,JSONUtil.toJsonStr(questionSubmitViewVO));
        }
    }
}
